import { RobotOutlined, UserOutlined } from "@ant-design/icons"
import { Avatar } from "antd"
import React, { memo, useEffect, useMemo, useState } from "react"

import MarkDownToHtml from "~components/MarkDownToHtml/MarkDownToHtml"
import type { ChatMessageType } from "~type/chatType"

const ChatItem = memo(
  (params: {
    item: ChatMessageType
    isend: boolean
    index?: number
    contents?: ChatMessageType[]
    isdelayed?: boolean
  }) => {
    // const [count, setCount] = useState(0)

    const chatEnd = useMemo(() => params.isend, [params.isend])
    const item = useMemo(() => {
      // console.log("params.item", params.item)
      return params.item && params.item.role && params.item
    }, [params.item])
    const contents = useMemo(() => params.contents, [params.contents])
    const index = useMemo(() => params.index, [params.index])
    const maxItem = useMemo(() => {
      const result = contents && index === contents.length - 1
      return result
    }, [contents, index])
    const isUser = useMemo(
      () => item && item.role && item.role === "user",
      [item]
    )
    const userAvators = useMemo(() => {
      if (item && item.role) {
        return (
          <div className="self-stretch">
            <Avatar
              className={
                (isUser ? "bg-primary-theme" : "bg-[#f9822d]") + " m-[.5rem] "
              }
              icon={isUser ? <UserOutlined></UserOutlined> : <RobotOutlined />}
            />
          </div>
        )
      }
    }, [item])

    const contentMemo = useMemo(() => {
      if (item && item.role) {
        return (
          <>
            {!isUser ? (
              <>
                <MarkDownToHtml
                  content={item && item.content}
                  isEnd={chatEnd}
                  isMax={maxItem}></MarkDownToHtml>
              </>
            ) : (
              <div>{item.content}</div>
            )}
          </>
        )
      }
    }, [item])
    const userOrBotClassStyle = useMemo(() => {
      if (item && item.role) {
        return (
          (isUser ? "flex-row-reverse" : "flex-row") +
          " flex m-[.5rem] relative min-w-0 w-full"
        )
      }
    }, [item])
    return (
      <div className={userOrBotClassStyle}>
        {userAvators}

        <div className="box-border min-w-0 flex  justify-center items-center p-[.5rem] rounded-lg border border-gray-200	border-solid">
          {contentMemo}
        </div>
      </div>
    )
  }
)
export default ChatItem
